/*
 * @Author: Setsuna
 * @Email: setsuna.xyz@qq.com
 * @FilePath: \src\pages\RolePermissionsManage\RolePermissions\list.tsx
 * @Date: 2022-12-05 10:44:43
 * @LastEditTime: 2023-08-15 14:26:13
 * @LastEditors: Setsuna
 */
import React from 'react'
import { Button, message, Input, Modal, Radio, Tooltip, TreeSelect, Select } from 'antd'
import { BaseListPage, IBaseListPageProps, IBaseListPageState, uaaApp, validators } from '../../../lib'
import { columnRenders } from '../../../lib/utils/columnRenders'
import { UdModal, UdModalForm } from '../../../lib/ui/UdModal'
import { http } from '../../../lib/core/http'
import TextArea from 'antd/lib/input/TextArea'
import SourceTree from '../component/SourceTree'
import apis from '@/apis/RolePermissions'
import systemApis from '@/apis/SystemSettings'
import UdSelect from '@/components/UdFormControls/UdSelect'
import udMainStore from '@/store/UdMain'
const confirm = Modal.confirm
const Option = Select.Option
const AddBtnAuth = 'user_auth_lzlj_add'
const UpdateBtnAuth = 'user_auth_lzlj_update'
const DeleteBtnAuth = 'user_auth_lzlj_delete'
const AddAuthBtnAuth = 'user_auth_lzlj_find_addRoleAuth'

const dataPermissionEnum = {
  SELF: '仅个人',
  AREA: '所在片区',
  BRAND: '品牌权限',
}

class RolePermissionsList extends BaseListPage<IRolePermissionsListProps, IRolePermissionsListState> {
  private brandList = udMainStore.brandList
  private profile = JSON.parse(sessionStorage.getItem('UaaSysInfo'))?.profile ?? {}
  protected saveParamsWithUrl: boolean = true

  /* 已选资源的父级id和已选id集合 */
  private allSourceCheckKeys: string[] = []

  constructor(props: IRolePermissionsListProps) {
    super(props)

    this.state = {
      title: '角色列表',
      positionTypeList: [],
      queryApi: params => {
        return http.post(apis.RoleList, { ...params, accountType: 0 })
      },
      conditions: [
        {
          label: '品牌公司',
          id: 'brandCode',
          render: <UdSelect showSearch options={this.brandList} />,
        },
        { id: 'roleName', label: '角色名' },
      ],
      rowKey: 'id',
      columns: [
        {
          title: '品牌公司',
          dataIndex: 'brandName',
          width: 100,
        },
        {
          title: '角色名',
          dataIndex: 'roleName',
          width: 200,
        },
        {
          title: '角色编码',
          dataIndex: 'roleCode',
          width: 80,
        },
        {
          title: '数据权限',
          dataIndex: 'dataPermissionEnum',
          width: 120,
          render: columnRenders.enum(dataPermissionEnum),
        },
        {
          title: '职位类型名称',
          dataIndex: 'positionNames',
          width: 400,
          render: (text, record) => {
            return (
              <Tooltip title={record.positionNames}>
                <div style={{ width: '400px', overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'ellipsis' }}>
                  {record.positionNames}
                </div>
              </Tooltip>
            )
          },
        },
        {
          title: '备注',
          dataIndex: 'remarkOne',
          width: 400,
          render: (text, record) => {
            return (
              <Tooltip title={record.remarkOne}>
                <div style={{ width: '300px', overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'ellipsis' }}>
                  {record.remarkOne}
                </div>
              </Tooltip>
            )
          },
        },
        {
          title: '创建人',
          dataIndex: 'createBy',
          width: 150,
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          width: 150,
        },
         {
          title: '修改人',
          dataIndex: 'updateName',
          width: 150,
        },
        {
          title: '修改时间',
          dataIndex: 'updateBy',
          width: 150,
        },
        {
          title: '操作',
          dataIndex: 'operate',
          width: '160px',
          fixed: 'right',
          allowCustomize: false,
          render: columnRenders.operate([
            {
              title: '编辑',
              auth: UpdateBtnAuth,
              action: (text: any, row: any) => this.edit(row),
            },
            {
              title: '资源配置',
              auth: AddAuthBtnAuth,
              action: (text: any, record: any) => this.setSource(record),
            },
            {
              title: '删除',
              auth: DeleteBtnAuth,
              action: (text: any, record: any) => {
                confirm({
                  title: '确定要删除该角色吗？',
                  onOk: () => {
                    return this.deleteRole(record)
                  },
                })
              },
            },
          ]),
        },
      ],
      leftBtns: [
        uaaApp.canUse(AddBtnAuth) && (
          <Button type="primary" onClick={this.addRole}>
            新增角色
          </Button>
        ),
      ],
      tableProps: {
        scroll: { x: true },
        rowSelection: null,
      },
    }
  }

  componentDidMount(): void {
    super.componentDidMount()
    this.getPositionTypeLis()
  }

  private setSource = row => {
    UdModal.open({
      title: '资源配置',
      content: (
        <UdModalForm
          items={[
            {
              id: 'authId',
              label: '资源权限',
              render: <SourceTree roleId={row.id} url={apis.AuthTreeList} onCheck={this.sourceTreeCheckHandle} />,
            },
          ]}
        />
      ),
      onOk: values => {
        values.roleId = row.id
        values.authId = this.allSourceCheckKeys
        return http.post(apis.AddRoleAuth, values).then(res => {
          message.success('配置成功')
        })
      },
    })
  }

  private addRole = () => {
    let { positionTypeList } = this.state
    UdModal.open({
      title: '新增角色',
      content: (
        <UdModalForm
          items={[
            { id: 'roleName', label: '角色名', rules: [validators.required, validators.max(20), validators.noSymbol] },
            { id: 'dataPermissionEnum', label: '数据权限', rules: [validators.required], render: <RadioCm /> },
            {
              label: '品牌公司',
              id: 'brandCode',
              rules: [this.profile?.roleId?.includes(1)?{required: false}:validators.required],
              render: <UdSelect showSearch options={this.brandList} />,
            },
            {
              id: 'positionIds',
              label: '职位类型',
              // rules: [validators.required],
              render: () => (
                <Select
                  getPopupContainer={triggerNode => triggerNode.parentElement}
                  mode="multiple"
                  optionFilterProp="children"
                >
                  {positionTypeList.map(({ name, code, id }) => (
                    <Option key={id} value={id}>
                      {name}
                    </Option>
                  ))}
                </Select>
              ),
            },
            {
              id: 'remarkOne',
              label: '备注',
              rules: [validators.max(40), validators.noSpecialSymbol],
              render: <TextArea />,
            },
          ]}
        />
      ),
      onOk: values => {
        values.positionTypeIds = values?.positionIds?.join(',')
        return http.post(apis.AddRole, values).then(res => {
          message.success('新增成功')
          this.query()
        })
      },
    })
  }

  private edit = row => {
    let { positionTypeList } = this.state
    let record = { ...row }
    record.positionIds = row?.positionIds?.split(',') ?? []
    UdModal.open({
      title: '编辑',
      width: '45%',
      content: (
        <UdModalForm
          labelCol={{ span: 3 }}
          wrapperCol={{ span: 21 }}
          items={[
            { id: 'roleName', label: '角色名', rules: [validators.required, validators.max(20), validators.noSymbol] },
            { id: 'dataPermissionEnum', label: '数据权限', rules: [validators.required], render: <RadioCm /> },
            {
              label: '品牌公司(只读)',
              id: 'brandName',
              render: () => {
                return <Input readOnly />
              }
            },
            {
              id: 'positionIds',
              label: '职位类型',
              // rules: [validators.required],
              render: () => (
                <Select
                  getPopupContainer={triggerNode => triggerNode.parentElement}
                  mode="multiple"
                  optionFilterProp="children"
                >
                  {positionTypeList.map(({ name, id, code }) => (
                    <Option key={id + '' + code} value={id + ''}>
                      {name}
                    </Option>
                  ))}
                </Select>
              ),
            },
            {
              id: 'remarkOne',
              label: '备注',
              rules: [validators.max(40), validators.noSpecialSymbol],
              render: <TextArea />,
            },
          ]}
          values={record}
        />
      ),
      onOk: values => {
        values.id = record.id
        values.positionTypeIds = values?.positionIds?.join(',')
        delete values.brandName
        return http.post(apis.UpdateRole, values).then(res => {
          message.success('编辑成功')
          this.query()
        })
      },
    })
  }

  private getPositionTypeLis = () => {
    http.get(systemApis.getPositionTypeAllList).then(res => {
      let { data = [] } = res ?? {}
      this.setState({ positionTypeList: data })
    })
  }

  private deleteRole = row => {
    return http.post(apis.DeleteRole, { id: row.id }).then(res => {
      message.success('删除成功')
      this.query()
    })
  }

  private sourceTreeCheckHandle = keys => {
    this.allSourceCheckKeys = keys
  }
}

interface IRolePermissionsListProps extends IBaseListPageProps {}

interface IRolePermissionsListState extends IBaseListPageState {
  positionTypeList: [Record<string, any>?]
}

export default RolePermissionsList

function RadioCm(props) {
  return (
    <Radio.Group onChange={props.onChange} value={props.value}>
      <Radio value="SELF">仅个人</Radio>
      <Radio value="AREA">所在片区</Radio>
      <Radio value="BRAND">品牌权限</Radio>
    </Radio.Group>
  )
}
